<?php
namespace app\common\model;

use think\Model;
use app\common\lib\Token;
use think\facade\Cache;

class SystemAdmin extends Model
{
	protected $table = "system_admin";

	static function login()
	{
		$username = request()->param('username');
		$password = request()->param('password');

		$admin = self::where('username', $username)->findOrEmpty();
		if ($admin->isEmpty()) {
			return json(['code' => 1001, 'message' => "账号不存在~", 'data' => ""]);
		}
		// 非空, 验证密码
		if (!password_verify($password, $admin['password'])) {
			return json(['code' => 1002, 'message' => "密码不正确~", 'data' => ""]);
		} else {
			// 删除密码
			unset($admin['password']);
			// 添加token
			$token = Token::create();
			$admin = $admin->toArray();
			// 设置 redis 缓存
			Cache::set($token, $admin, 300);
			$data['token'] = $token;
			$data['userInfo'] = $admin;
			return json(['code' => 200, 'message' => "成功登录~", 'data' => $data]);
		}
	}
}
